import React, { useEffect,useState } from 'react';
import { Form,
  Input, 
  Select,
  Drawer,
  Button,
  PageHeader,
  Divider,
  Row,
  Col,
  Checkbox,
  Tag,
  Table,
  Space,
 } from 'antd';
import {getDictCode,getDictCodeLabel} from '@/utils/DataDictUtils';
import moment from 'moment';
import '../index.less';
import SelectRoleModal from './SelectRoleModal';

const { Option } = Select;
const { TextArea } = Input;
const FormItem = Form.Item;
 

const EditForm = props => {
  /*这些参数由index.jsx传过来的 */
  const { dispatch,visible, current, onCancel, onSubmit } = props;
  const [roles, setRoles] = useState([]);
  const [selectRoleModalVisible, setSelectRoleModalVisible] = useState(false);
  const [editDisabled, setEditDisabled] = useState(false);
  const [loading, setLoading] = useState(false);
  /*通过useForm来获取一个form对象 */
  const [editForm] = Form.useForm();
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    setLoading(false);
    if (editForm && visible) {
      setEditDisabled(false);
      editForm.resetFields();
      setRoles([]);
      editForm.setFieldsValue({
        isAdmin:true
      });
    }
    if (editForm && visible && current) {
      editForm.setFieldsValue(current);
      if(current && current.sex){
        editForm.setFieldsValue({
          sex:current.sex.toString()
        })
      }
 
      if(current.roles){
        setRoles(current.roles);
      }

      setEditDisabled(false);
    }

  }, [props.visible]);

  const onFinish =(values)=>{
    setLoading(true);
      
    if(roles && roles.length > 0){
      values.roles = roles.map((item)=>{ return item.roleId});
    }
    if(values.isAccount){
      values.access={
        account:values.phone,
        isAdmin:values.isAdmin,
        roles:values.roles,
      }
    }else{
      values.access=null;
    }
    onSubmit(values,submitCallback);
  }

  const submitCallback = (resp)=>{
    setLoading(false);
  }

  const handleSubmit = () => {
    editForm.submit();
  };

  const onClose =()=>{
    onCancel();
  }
 
 

const handleRoleDelete=(item)=>{
  let roleId = item.roleId;
    let tempData = roles.filter((item)=>(item.roleId!==roleId));
    setRoles(tempData);
}
 

const handleSelectRoleModalOpen=()=>{
  setSelectRoleModalVisible(true);
}

 

const handleSelectRoleModalCancel=()=>{
  setSelectRoleModalVisible(false);
}

 

const handleSelectRoleModalOk=(selectRole)=>{
  setSelectRoleModalVisible(false);
  if(selectRole && selectRole.length > 0){
    let tempArr = roles.concat();
    selectRole.forEach((item)=>{
      const role = roles.find((r) => r.roleId === item.roleId);
      if(!role){
        tempArr.push(item);
      }
    });
    console.log(tempArr);
    setRoles(tempArr);
  }else{
    setRoles([]);
  }
  
}
 

  const sexOptions = getDictCode('sex').map(d => (
    <Option key={d.codeValue}>{d.codeLabel}</Option>
  ));
 

  return (
    <>
    <Drawer
          title={current?'编辑平台用户':"添加平台用户"}
          width={820}
          onClose={onClose}
          visible={visible}
          bodyStyle={{ paddingBottom: 80 }}
          footer={
            <div
              style={{
                textAlign: 'right',
              }}
            >
              <Button onClick={onClose} style={{ marginRight: 8 }}>
                取消
              </Button>
              <Button onClick={onClose} style={{ marginRight: 8,display: current?"":"none" }}>
                {current && current.status===1?'停用':'启用'}
              </Button>
              <Button onClick={handleSubmit} type="primary" loading={loading}>
                保存
              </Button>
            </div>
          }
        >
        
        <Form
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 14,
          }}
          layout="horizontal"
          name='editForm' 
          form={editForm} 
          onFinish={onFinish}
        >
          <Row>
            <Col span={18}>
              <FormItem label='登录名' name='loginName' rules={[
                    {
                      required: true,
                      message: '登录名不能为空',
                    },
                  ]}>
                  <Input
                    allowClear
                    autoComplete="off"
                    maxLength={100}
                    placeholder='请输入登录名'
                    disabled={editDisabled}
                  />
              </FormItem>
            </Col>
          </Row>
          <Row>
            {/* <Col span={7}>
              <FormItem label='性别' name='sex'>
                <Select
                    allowClear
                    placeholder='请选择性别'
                    style={{ width: 120 }}
                  >
                    {sexOptions}
                  </Select>
              </FormItem>
            </Col> */}
            <Col  span={18}>
            <FormItem label='用户名' name='userName' rules={[
                    {
                      required: true,
                      message: '用户名不能为空',
                    },
                  ]}>
                  <Input
                    allowClear
                    autoComplete="off"
                    maxLength={100}
                    placeholder='请输入用户名'
                    disabled={editDisabled}
                  />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={18}>
              <FormItem label='手机号' name='phone' rules={[
                    {
                      required: true,
                      message: '手机号不能为空',
                    },
                    {
                      pattern: /^1[3456789]\d{9}$/, 
                      message: '请输入正确的手机号'
                    }
                  ]}>
                  <Input
                    allowClear
                    autoComplete="off"
                    maxLength={100}
                    placeholder='请输入手机号'
                    disabled={editDisabled}
                  />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={18}>
              <FormItem label='密码' name='password' rules={[
                    {
                      required: true,
                      message: '密码不能为空',
                    }
                  ]}>
                  <Input.Password
                    allowClear
                    autoComplete="off"
                    maxLength={100}
                    placeholder='请输入密码'
                    disabled={editDisabled}
                  />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={18}>
              <FormItem label='确认密码' name='confirm' dependencies={['password']}  hasFeedback rules={[
                    {
                      required: true,
                      message: '密码不能为空',
                    },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次输入的密码不一致!'));
                      },
                    }),
                  ]}>
                  <Input.Password
                    allowClear
                    autoComplete="off"
                    maxLength={100}
                    placeholder='请输入密码'
                    disabled={editDisabled}
                  />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem labelCol={{ span: 6,}} wrapperCol={{span: 12,}} label='系统权限' name="isAdmin" valuePropName="checked" >
                <Checkbox>系统管理员</Checkbox>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem labelCol={{ span: 6,}} wrapperCol={{span: 12,}} label='系统权限' >
                {roles && roles.map((item)=>(
                    <Tag closable style={{marginTop:'5px'}} onClose={()=>{handleRoleDelete(item)}} key={item.roleId} >
                      {item.roleName}
                    </Tag>
                ))}
              </FormItem>
            </Col>
            <Col>
                  <Button onClick={handleSelectRoleModalOpen}>选择系统权限</Button>
            </Col>
          </Row>
          
        </Form>
        </Drawer>
        <SelectRoleModal 
          current={current}
          roles={roles}
          visible={selectRoleModalVisible}
          handleCancel={handleSelectRoleModalCancel}
          handleSelect={handleSelectRoleModalOk}
          dispatch={dispatch}
        />
    </>
  );
};
/*antd pro V4 跟 antd proV3 不同不再需要Form.create方法了 */
export default EditForm;
